package com.ruoyi.Apps.Utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AppUtils {
    private static int KEY_INDEX = 8;

    private static int NUM_INDEX = 15;

    private static int S_KEY_INDEX = 3;

    private static int S_NUM_INDEX = 9;


    public static String getSystemOutId(Long id) {
        return getSystemOutId_v2( id );
//        String uuid = UUID.fastUUID().toString().replaceAll("-","");
//        String firstKey = uuid.substring(0, 1);
//        int keyNum = Character.getNumericValue(firstKey.toCharArray()[0]);
//        int num = keyNum % 10 + NUM_INDEX;
//        String idString = String.valueOf(id);
//        int idLength = idString.length();
//        String id2 = uuid.substring(0,KEY_INDEX)
//                + idLength
//                + uuid.substring(KEY_INDEX+1,num)
//                + id
//                + uuid.substring(num+idLength);
//        return id2;
    }

    public static String getSystemTimeId(Date date, Long userId) {
        String DDmm = DateFormatUtils.format(date, "MMddssSSS");
        return generateRandomCode(userId)  + DDmm;
    }

    public static String getSystemTimeId() {
        return getSystemTimeId(new Date(), SecurityUtils.getUserId());
    }

    public static String getSystemTimeId(Long userId) {
        return getSystemTimeId(new Date(), userId);
    }

    public static String generateRandomCode(long userId) {
        String base = String.valueOf(100000 + userId);
        if (base.length() < 3) return base;

        char[] chars = base.toCharArray();
        char randomChar1 = (char) ('A' + (int) (Math.random() * 26));
        char randomChar2 = (char) ('A' + (int) (Math.random() * 26));

        // 随机选择两个不同的中间位置
        int pos1, pos2;
        do {
            pos1 = 1 + (int) (Math.random() * (chars.length - 2));
            pos2 = 1 + (int) (Math.random() * (chars.length - 2));
        } while (pos1 == pos2 && chars.length > 3); // 确保位置不同，除非长度太小

        chars[pos1] = randomChar1;
        chars[pos2] = randomChar2;

        return new String(chars);
    }

    public static String md5(String str) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }

        // 将输入字符串转换为字节数组，并计算其哈希值
        byte[] hashBytes = md.digest(str.getBytes());

        // 将字节数组转换为十六进制字符串表示
        StringBuilder hexString = new StringBuilder();
        for (byte hashByte : hashBytes) {
            String hex = Integer.toHexString(0xff & hashByte);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static Long getSystemInnerId(String uuid) {
        return getSystemInnerId_v2( uuid );
//        if (StringUtils.isNull(uuid)) return null;
//        String firstKey = uuid.substring(0, 1);
//        int keyNum = Character.getNumericValue(firstKey.toCharArray()[0]);
//        int num = keyNum % 10 + NUM_INDEX;
//        try {
//            int idLength = Integer.parseInt(uuid.substring(KEY_INDEX, KEY_INDEX + 1));
//            String idString = uuid.substring(num, num+idLength);
//            Long id = Long.valueOf(idString);
//            return id;
//        }catch (Exception e) {
//            throw new ServiceException("无效的内容");
//        }
    }

    public static String getSystemOutId_v2(Long id) {
        String uuid = UUID.fastUUID().toString().replaceAll("-","").substring( 0, 24 );
        String firstKey = uuid.substring(0, 1);
        int keyNum = Character.getNumericValue(firstKey.toCharArray()[0]);
        int num = keyNum % 5 + S_NUM_INDEX;
        String idString = String.valueOf(id);
        int idLength = idString.length();
        String id2 = uuid.substring(0,S_KEY_INDEX)
                + idLength
                + uuid.substring(S_KEY_INDEX+1,num)
                + id
                + uuid.substring(num+idLength);
        return id2;
    }

    public static Long getSystemInnerId_v2(String uuid) {
        if (StringUtils.isNull(uuid)) return null;
        String firstKey = uuid.substring(0, 1);
        int keyNum = Character.getNumericValue(firstKey.toCharArray()[0]);
        int num = keyNum % 5 + S_NUM_INDEX;
        try {
            int idLength = Integer.parseInt(uuid.substring(S_KEY_INDEX, S_KEY_INDEX + 1));
            String idString = uuid.substring(num, num+idLength);
            Long id = Long.valueOf(idString);
            return id;
        }catch (Exception e) {
            throw new ServiceException("无效的内容");
        }
    }
    public static String filterFilePath(String path) {
        if (StringUtils.isEmpty( path )) return "";
        String profile = RuoYiConfig.getProfile();
        if (path.startsWith( profile )) {
            return path;
        }
        return path.replace( "/home/data", profile );
    }

    /**
     * 从输入字符串中提取并解析 JSON 内容。
     *
     * @param inputString 输入的字符串
     * @return 解析后的 JSON 对象，或者包含错误信息的 JSON 对象
     */
    public static String extractJsonFromString(String inputString) {
        // 检查输入是否为 null 或空字符串
        if (StringUtils.isEmpty(inputString)) {
            return inputString;
        }

        // 去除可能存在的代码块标记
        inputString = inputString.replaceAll("```json\\s*|\\s*```", "").trim();
        System.out.println("处理后的输入: " + inputString); // 调试信息

        // 使用正则表达式匹配 JSON 格式的内容
        String jsonPattern = "\\{.*?\\}";
        Pattern pattern = Pattern.compile(jsonPattern, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(inputString);

        if (matcher.find()) {
            String jsonString = matcher.group(0);
            return jsonString;
        } else {
            // 如果没有匹配到 JSON，返回错误信息
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("error", inputString);
            return errorResponse.toJSONString();
        }
    }

    /**
     * 从输入字符串中提取并解析 JSON 内容。
     *
     * @param inputString 输入的字符串
     * @return 解析后的 JSON 对象，或者包含错误信息的 JSON 对象
     */
    public static String extractJsonFromStringV2(String inputString) {
        // 检查输入是否为 null 或空字符串
        if (StringUtils.isEmpty(inputString)) {
            return null;
        }

        // 查找包含 ```json 和 ``` 的片段
        String startTag = "```json";
        String endTag = "```";

        int startIndex = inputString.indexOf(startTag);
        int endIndex = inputString.indexOf(endTag, startIndex + startTag.length());

        // 判断是否符合条件
        if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
            // 提取中间内容并移除 \n
            String cleanJson = inputString.substring(startIndex + startTag.length(), endIndex);
            // 第一步：把带转义符的字符串反序列化成真正的字符串
            String jsonText = JSON.parse("\"" + cleanJson + "\"").toString();
            JSONObject inner = JSON.parseObject(jsonText);;
            return inner.toJSONString();
        } else {
            try {
                JSONObject jsonObject = JSONObject.parseObject(inputString);
                String cleanJson = jsonObject.getString("transcription");
                if (StringUtils.isNotEmpty(cleanJson)) {
//                    String jsonText = JSON.parse("\"" + cleanJson + "\"").toString();
                    JSONObject inner = JSON.parseObject(cleanJson);
                    return inner.toJSONString();
                }
            }catch (Exception e){}
        }

        // 不符合条件，原样返回
        return inputString;
    }

    public static String pathLocal2http(String path) {
        if(StringUtils.isEmpty(path)
                || path.startsWith("https://")
                || path.startsWith("http://")) {
            return path;
        }
        return path.replace("/home/ruoyi/uploadPath", "/profile");
    }

    public static String pathHttp2local(String path) {
        return null;
    }

    public static void main(String[] args) {
        System.out.println(getSystemTimeId(new Date(), 65l));
    }

    /**
     * 方法1: 使用正则表达式提取数字部分
     */
    public static BigDecimal extractNumberWithRegex(String currencyStr) {
        if (currencyStr == null || currencyStr.trim().isEmpty()) {
            return BigDecimal.ZERO;
        }

        // 匹配数字（包括小数点和负号）
        Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
        Matcher matcher = pattern.matcher(currencyStr);

        if (matcher.find()) {
            return new BigDecimal(matcher.group());
        } else {
            return BigDecimal.ZERO;
        }
    }
}
